<template>
  <portal ref="tableRef" :action-width="180" table-id="position">
    <template #action="{ portalConfig, column, record }">
      <div style="display: flex; justify-content: space-around">
        <a-button v-if="isEmpty(record.customerNumber)" type="link" @click="openBindMemberModal(record)">
          任命成员
        </a-button>
        <a-button v-if="isNotEmpty(record.customerNumber)" type="link" @click="unbindMember(record)">取消任命</a-button>
        <a-button
          v-if="routeStore.isButtonEnable('bindMedication')" type="link"
          @click="bindMedication(portalConfig, column, record)">授权药品
        </a-button>
      </div>
    </template>
  </portal>
  <a-modal
    :open="bindMemberForm.show"
    title="任命成员"
    width="30%"
    @cancel="resetBindMemberForm"
    @close="resetBindMemberForm"
    @ok="handleBindMemberModalConfirm">
    <a-tabs v-model:activeKey="activeTabKey" style="margin-left: 10px" @change="changeTab">
      <a-tab-pane key="CREATE" tab="新建用户">
        <a-form :label-col="{ span: 3 }" :model="createMemberForm">
          <a-form-item
            :rules="[
              { required: true, message: '请输入新建用户账号' }]"
            has-feedback
            label="账号"
            name="userName">
            <a-input v-model:value="createMemberForm.userName" autocomplete="off" placeholder="新建用户账号" />
          </a-form-item>
          <a-form-item
            :rules="[
              { required: true, message: '请输入新建用户姓名' }]"
            has-feedback
            label="姓名"
            name="name">
            <a-input v-model:value="createMemberForm.name" autocomplete="off" placeholder="新建用户姓名" />
          </a-form-item>
          <a-form-item
            :required="false"
            :rules="[
              { message: '手机号码格式不正确', pattern: '^1[3-9]\\d{9}$' }]"
            label="手机号码"
            name="phoneNumber">
            <a-input v-model:value="createMemberForm.phoneNumber" autocomplete="off" placeholder="新建用户手机号码" />
          </a-form-item>
        </a-form>
      </a-tab-pane>
      <a-tab-pane key="BIND" tab="已注册用户">
        <a-form :label-col="{ span: 3 }" :model="bindMemberForm">
          <a-form-item
            :rules="[
              { required: true, message: '请输入姓名或通过手机号查验姓名' },
              { validator: nameValidator, trigger: 'blur' }]"
            has-feedback
            label="姓名"
            name="name">
            <a-input v-model:value="bindMemberForm.name" autocomplete="off" placeholder="目标用户姓名" />
          </a-form-item>
          <a-form-item
            :required="false"
            :rules="[
              { message: '手机号码格式不正确', pattern: '^1[3-9]\\d{9}$' },
              { validator: phoneNumberValidator, trigger: 'blur' }]"
            label="手机号码"
            name="phoneNumber">
            <a-input v-model:value="bindMemberForm.phoneNumber" autocomplete="off" placeholder="目标手机号码" />
          </a-form-item>
        </a-form>
      </a-tab-pane>
    </a-tabs>

  </a-modal>
  <portal-bind-modal
    ref="portalBindModalRef"
    attach-entity="medication"
    entity="position"
    title="药品"
  />
</template>

<script lang="ts" setup>
import { Modal } from 'ant-design-vue'
import { createVNode } from 'vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { isEmpty, isNotEmpty } from '@/framework/utils/common'
import { bindPosition, createAndBindPosition, unBindPosition } from '@/apis/position'
import { userExisted } from '@/framework/apis/admin/user'
import { ColumnType, TableConfigType } from '@/framework/components/common/portal/type'
import pinia from "@/framework/store/index";
import { useRouteStore } from '@/framework/store/route'

const routeStore = useRouteStore(pinia)
const tableRef = ref()
const activeTabKey = ref('CREATE')
const createMemberForm = reactive({
  positionId: '',
  userName: '',
  name: '',
  phoneNumber: '',
  show: false
})
const bindMemberForm = reactive({
  positionId: '',
  name: '',
  phoneNumber: '',
  customerNumber: '',
  show: false
})
const phoneNumberValidator = () => {
  if (isNotEmpty(bindMemberForm.phoneNumber)) {
    if (/^1[3-9]\d{9}$/.test(bindMemberForm.phoneNumber)) {
      return userExisted(bindMemberForm.phoneNumber).then(res => {
        bindMemberForm.customerNumber = res.payload.customerNumber
        bindMemberForm.name = res.payload.label
      })
    } else {
      return new Promise(() => {
        throw new Error('手机号码格式不正确')
      })
    }
  }
}
const nameValidator = () => {
  if (isNotEmpty(bindMemberForm.name)) {
    return userExisted(undefined, undefined, undefined, bindMemberForm.name, undefined).then(res => {
      bindMemberForm.customerNumber = res.payload.customerNumber
      bindMemberForm.name = res.payload.label
    })
  } else {
    return new Promise(() => {
      throw new Error('请输入姓名或通过手机号查验姓名')
    })
  }
}
const openBindMemberModal = (record: any) => {
  bindMemberForm.positionId = record.id
  createMemberForm.positionId = record.id
  bindMemberForm.show = true
}
const handleBindMemberModalConfirm = () => {
  if (activeTabKey.value === 'BIND') {
    bindMember(bindMemberForm.positionId, bindMemberForm.customerNumber).then(() => {
      resetBindMemberForm()
      bindMemberForm.show = false
      tableRef.value.queryData()
    })
  } else {
    createAndBindMember(createMemberForm.positionId, createMemberForm.userName, createMemberForm.name, createMemberForm.phoneNumber).then(() => {
      resetCreateAndBindMemberForm()
      bindMemberForm.show = false
      tableRef.value.queryData()
    })
  }
}
const resetBindMemberForm = () => {
  bindMemberForm.positionId = ''
  bindMemberForm.customerNumber = ''
  bindMemberForm.phoneNumber = ''
  bindMemberForm.name = ''
  bindMemberForm.show = false
}
const resetCreateAndBindMemberForm = () => {
  createMemberForm.positionId = ''
  createMemberForm.userName = ''
  createMemberForm.phoneNumber = ''
  createMemberForm.name = ''
  createMemberForm.show = false
}
const bindMember = (positionId: number | string, customerNumber: string) => {
  return bindPosition(positionId, customerNumber).then(tableRef.value.queryData)
}
const createAndBindMember = (positionId: number | string, userName: string, name: string, phoneNumber: string) => {
  return createAndBindPosition(positionId, userName, name, phoneNumber).then(tableRef.value.queryData)
}
const unbindMember = (record: any) => {
  Modal.confirm({
    title: '注意',
    icon: createVNode(ExclamationCircleOutlined),
    content: createVNode('div', { style: 'color:red;' }, '该岗位人员即将被删除,请确认。'),
    onOk() {
      unBindPosition(record.id).then(tableRef.value.queryData)
    },
    onCancel() {

    }
  })
}

const portalBindModalRef = ref()
const bindMedication = (portalConfig: TableConfigType, column: ColumnType, record: any) => {
  console.log(record, record[portalConfig.rowKey])
  portalBindModalRef.value.showBindDialogBox(record[portalConfig.rowKey], record)
}
const changeTab = (key: string) => {
  activeTabKey.value = key
  resetBindMemberForm()
  resetCreateAndBindMemberForm()
}
</script>

<style scoped>

</style>
